package com.lifeng.zk.nativeapi.watch;

import org.apache.zookeeper.*;

import java.util.concurrent.CountDownLatch;

/**
 * Created by lifeng on 2018/6/13.
 * 原生的watch太难用了
 */
public class WatchMain {
    private static String zkUrl = "127.0.0.1:2181";
    //连接超时时间
    private static Integer sessionOutTime = 5000;
    /** 信号量，阻塞程序执行，用于等待zookeeper连接成功，发送成功信号 */
    private static final CountDownLatch connectedSemaphore = new CountDownLatch(1);

    private static ZooKeeper zk;

    public static void main(String[] args) throws Exception {
        zk = new ZooKeeper(zkUrl, sessionOutTime, new Watcher() {
            public void process(WatchedEvent watchedEvent) {
                //获取事件的状态
                Event.KeeperState state = watchedEvent.getState();
                //获取事件类型
                Event.EventType type = watchedEvent.getType();
                //如果是建立连接
                if(Event.KeeperState.SyncConnected.equals(state)){
                    if(Event.EventType.None.equals(type)){//None 是连接
                        //如果建立连接成功，则发送信号量，让后续阻塞程序向下执行
                        //connectedSemaphore.countDown();
                        System.out.println("zk 建立连接");
                    }
                }
            }
        });
        //connectedSemaphore.await();
        MyNodeWatch myNodeWatch = new MyNodeWatch();
        zk.exists("/test",myNodeWatch);
        Thread.sleep(100000000);
    }
}
